<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

const list = ref<any[]>([])
const loading = ref(false)

async function fetchList() {
  loading.value = true
  try {
    const { data } = await request.get('/api/admin/admin-gift-sends')
    list.value = data
  } catch (error) {
    console.error('선물 발송 기록 가져오기 실패:', error)
    ElMessage.error('선물 발송 기록 가져오기 실패')
  } finally {
    loading.value = false
  }
}

// 格式化数字
const formatNumber = (num: number | string | undefined | null) => {
  if (num === undefined || num === null) return '0'
  const n = typeof num === 'string' ? parseInt(num) || 0 : num
  return n.toLocaleString()
}

// 格式化时间
const formatTime = (time: string) => {
  if (!time) return '-'
  return new Date(time).toLocaleString('ko-KR', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

onMounted(fetchList)
</script>

<template>
  <div class="gift-sends">
    <h2>선물 발송 기록</h2>
    <el-button type="primary" @click="fetchList" :loading="loading">새로고침</el-button>
    <el-table :data="list" stripe style="margin-top:12px">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column label="라이브 방" min-width="160">
        <template #default="{ row }">{{ row.liveRoom?.title || row.liveRoomId }}</template>
      </el-table-column>
      <el-table-column label="선물" min-width="140">
        <template #default="{ row }">{{ row.gift?.name || row.giftId }}</template>
      </el-table-column>
      <el-table-column label="수량" width="80">
        <template #default="{ row }">{{ formatNumber(row.quantity) }}</template>
      </el-table-column>
      <el-table-column label="단가(포인트)" width="120">
        <template #default="{ row }">{{ formatNumber(row.unitPricePoints) }}</template>
      </el-table-column>
      <el-table-column label="총 포인트" width="120">
        <template #default="{ row }">{{ formatNumber(row.totalPoints) }}</template>
      </el-table-column>
      <el-table-column label="발송자" min-width="140">
        <template #default="{ row }">{{ row.sender?.loginId || row.senderUserId }}</template>
      </el-table-column>
      <el-table-column label="시간" min-width="180">
        <template #default="{ row }">{{ formatTime(row.createdAt) }}</template>
      </el-table-column>
    </el-table>
  </div>
</template>

<style scoped>
.gift-sends{padding:20px}
</style>

